﻿// Controllers/EmployeeController.cs
using System;
using System.Linq;
using System.Web.Mvc;
using WebApplication1.Models;
using System.Data.Entity;
using System.Collections.Generic;
using WebApplication1.Utilities; // 确保这个引用存在

namespace WebApplication1.Controllers
{
    [AuthorizeRole("Employee")]
    public class EmployeeController : BaseController
    {
        private ExamDbContext db = new ExamDbContext();
        // 辅助方法：批量获取翻译文本
        private Dictionary<string, string> GetTranslations(params string[] keys)
        {
            return LanguageManager.GetTexts(keys);
        }
        // 员工首页
        public ActionResult Index()
        {
            var activeExams = db.Exams.Where(e => e.IsActive).ToList();
            // 批量获取翻译文本
            var translations = GetTranslations(
                "ActiveExams", "TakeExam", "MyExamResults", "ExamName",
                "Description", "Duration", "Minutes", "WelcomeMessage"
            );

            ViewBag.PageTitle = translations["ActiveExams"];
            ViewBag.TakeExam = translations["TakeExam"];
            ViewBag.MyExamResults = translations["MyExamResults"];
            ViewBag.ExamName = translations["ExamName"];
            ViewBag.Description = translations["Description"];
            ViewBag.Duration = translations["Duration"];
            ViewBag.Minutes = translations["Minutes"];

            return View(activeExams);
        }

        public ActionResult TakeExam(int id)
        {
            var exam = db.Exams
                .Include("Questions")
                .Include("Questions.Options")
                .FirstOrDefault(e => e.ExamId == id);

            if (exam == null)
            {
                var translations1 = GetTranslations("ExamNotFound", "Back");
                TempData["ErrorMessage"] = translations1["ExamNotFound"];
                return RedirectToAction("Index");
            }

            var translations = GetTranslations(
            "TakeExam", "Question", "Score", "SingleChoice",
            "MultipleChoice", "TrueFalse", "FillBlank", "Submit",
            "Back", "Next", "Previous", "Finish", "True", "False",
            "CorrectAnswer", "YourAnswer", "Options"
        );

            ViewBag.PageTitle = translations["TakeExam"] + " - " + exam.ExamName;
            ViewBag.Question = translations["Question"];
            ViewBag.Score = translations["Score"];
            ViewBag.SingleChoice = translations["SingleChoice"];
            ViewBag.MultipleChoice = translations["MultipleChoice"];
            ViewBag.TrueFalse = translations["TrueFalse"];
            ViewBag.FillBlank = translations["FillBlank"];
            ViewBag.Submit = translations["Submit"];
            ViewBag.Back = translations["Back"];
            ViewBag.Next = translations["Next"];
            ViewBag.Previous = translations["Previous"];
            ViewBag.Finish = translations["Finish"];
            ViewBag.True = translations["True"];
            ViewBag.False = translations["False"];
            ViewBag.CorrectAnswer = translations["CorrectAnswer"];
            ViewBag.YourAnswer = translations["YourAnswer"];
            ViewBag.Options = translations["Options"];

            // 确保使用有效的 DateTime 值
            var now = DateTime.Now;

            // 检查 DateTime 是否在有效范围内 (1753-01-01 到 9999-12-31)
            if (now < new DateTime(1753, 1, 1) || now > new DateTime(9999, 12, 31))
            {
                now = DateTime.UtcNow; // 使用 UTC 时间作为备选
            }

            // 创建考试结果记录
            var examResult = new ExamResult
            {
                UserId = (int)Session["UserId"],
                ExamId = id,
                StartTime = now,
                TotalScore = exam.Questions.Where(x=>x.IsActive).Sum(q => q.Score)
            };

            db.ExamResults.Add(examResult);
            db.SaveChanges();

            Session["CurrentExamResultId"] = examResult.ResultId;

            return View(exam);
        }

        [HttpPost]
        public ActionResult SubmitExam(int examId, FormCollection form)
        {
            // 检查 Session 中是否有考试结果 ID
            if (Session["CurrentExamResultId"] == null)
            {
                return RedirectToAction("Index");
            }

            var examResultId = (int)Session["CurrentExamResultId"];
            var examResult = db.ExamResults.Find(examResultId);

            if (examResult == null)
            {
                return HttpNotFound();
            }

            var exam = db.Exams
                .Include("Questions")
                .Include("Questions.Options")
                .FirstOrDefault(e => e.ExamId == examId);

            if (exam == null)
            {
                return HttpNotFound();
            }

            int totalScore = 0;

            foreach (var question in exam.Questions.Where(x => x.IsActive))
            {
                var userAnswerValue = form["question_" + question.QuestionId];
                var userAnswerTextValue = form["answer_text_" + question.QuestionId]; // 直接获取用户答案的文字描述
                var correctAnswerValue = form["correct_" + question.QuestionId]; // 获取打乱顺序后的正确答案序号
                var correctAnswerTextValue = form["correct_text_" + question.QuestionId]; // 获取打乱顺序后的正确答案描述
                bool isCorrect = false;
                int score = 0;

                if (!string.IsNullOrEmpty(userAnswerValue))
                {
                    isCorrect = CheckAnswer(question, userAnswerValue, correctAnswerValue);
                    score = isCorrect ? question.Score : 0;
                    totalScore += score;
                }

                // 保存用户答案
                var userAnswer = new UserAnswer
                {
                    ResultId = examResultId,
                    QuestionId = question.QuestionId,
                    Answer = userAnswerValue ?? "",
                    AnswerText = userAnswerTextValue ?? "", // 直接使用前端传来的用户答案文字描述
                    IsCorrect = isCorrect,
                    Score = score,
                    CorrectAnswer = correctAnswerValue ?? question.CorrectAnswer, // 保存打乱顺序后的正确答案序号
                    CorrectAnswerText = correctAnswerTextValue ?? "", // 直接使用前端传来的正确答案文字描述
                };
                if (question.QuestionType == "Fill")
                {
                    userAnswer.CorrectAnswerText = question.CorrectAnswer; // 对于填空题，将用户答案保存为文字描述
                }
                db.UserAnswers.Add(userAnswer);
            }

            // 更新考试结果
            examResult.EndTime = DateTime.Now;
            examResult.Score = totalScore;
            db.Entry(examResult).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            Session.Remove("CurrentExamResultId");

            return RedirectToAction("ExamResult", new { id = examResultId });
        }
        // 获取用户答案的文字描述
        private string GetUserAnswerText(Question question, string userAnswerValue)
        {
            if (string.IsNullOrEmpty(userAnswerValue))
                return "";

            switch (question.QuestionType)
            {
                case "Single":
                case "Multiple":
                    var answerLabels = userAnswerValue.Split(',');
                    var answerTexts = new List<string>();

                    foreach (var label in answerLabels)
                    {
                        var option = question.Options.FirstOrDefault(o => o.OptionLabel == label.Trim());
                        if (option != null)
                        {
                            answerTexts.Add(option.OptionText);
                        }
                    }

                    return string.Join("; ", answerTexts);

                case "TrueFalse":
                    return userAnswerValue == "T" ? "正确" : "错误";

                case "Fill":
                    return userAnswerValue;

                default:
                    return userAnswerValue;
            }
        }

        // 获取正确答案的文字描述
        private string GetCorrectAnswerText(Question question, string correctAnswerValue)
        {
            if (string.IsNullOrEmpty(correctAnswerValue))
                return "";

            switch (question.QuestionType)
            {
                case "Single":
                case "Multiple":
                    var answerLabels = correctAnswerValue.Split(',');
                    var answerTexts = new List<string>();

                    foreach (var label in answerLabels)
                    {
                        var option = question.Options.FirstOrDefault(o => o.OptionLabel == label.Trim());
                        if (option != null)
                        {
                            answerTexts.Add(option.OptionText);
                        }
                    }

                    return string.Join("; ", answerTexts);

                case "TrueFalse":
                    return correctAnswerValue == "T" ? "正确" : "错误";

                case "Fill":
                    return question.CorrectAnswer;

                default:
                    return question.CorrectAnswer;
            }
        }

        // 检查答案是否正确（更新版本）
        private bool CheckAnswer(Question question, string userAnswer, string correctAnswer)
        {
            switch (question.QuestionType)
            {
                case "Single":
                case "TrueFalse":
                    return userAnswer == correctAnswer;
                case "Multiple":
                    var userAnswers = userAnswer.Split(',').OrderBy(x => x).ToArray();
                    var correctAnswers = correctAnswer.Split(',').OrderBy(x => x).ToArray();
                    return userAnswers.SequenceEqual(correctAnswers);
                case "Fill":
                    // 填空题可能需要模糊匹配
                    return userAnswer.Equals(question.CorrectAnswer, StringComparison.OrdinalIgnoreCase);
                default:
                    return false;
            }
        }

        // 填空题答案检查方法
        private bool CheckFillAnswer(string userAnswer, string correctAnswer)
        {
            // 将用户答案和正确答案都按逗号分割并去除空格
            var userAnswers = userAnswer.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();
            var correctAnswers = correctAnswer.Split(',').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).ToArray();

            // 检查答案数量是否一致
            if (userAnswers.Length != correctAnswers.Length)
                return false;

            // 检查每个答案是否匹配（顺序可能不重要，根据需求调整）
            // 这里假设填空题答案顺序是重要的
            for (int i = 0; i < userAnswers.Length; i++)
            {
                if (!string.Equals(userAnswers[i], correctAnswers[i], StringComparison.OrdinalIgnoreCase))
                {
                    return false;
                }
            }

            return true;
        }
        // 查看考试结果
        public ActionResult ExamResult(int id)
        {
            var result = db.ExamResults
                .Include("User")
                .Include("Exam")
                .Include("UserAnswers")
                .Include("UserAnswers.Question")
                .FirstOrDefault(r => r.ResultId == id);

            if (result == null)
            {
                return HttpNotFound();
            }

            // 批量获取翻译文本
            var translations = GetTranslations(
                "ExamResult", "ExamInfo", "UserName", "StartTime",
                "EndTime", "TimeUsed", "TotalScore", "Score",
                "Percentage", "Pass", "Fail", "NotCompleted",
                "Hours", "Minutes", "Seconds", "Back",
                "Question", "YourAnswer", "CorrectAnswer", "Explanation",
                "SingleChoice", "MultipleChoice", "TrueFalse", "FillBlank",
                "True", "False", "TrueValue", "FalseValue"
            );

            // 设置 ViewBag 用于视图中的文本显示
            ViewBag.ExamResult = translations["ExamResult"];
            ViewBag.ExamInfo = translations["ExamInfo"];
            ViewBag.UserName = translations["UserName"];
            ViewBag.StartTime = translations["StartTime"];
            ViewBag.EndTime = translations["EndTime"];
            ViewBag.TimeUsed = translations["TimeUsed"];
            ViewBag.TotalScore = translations["TotalScore"];
            ViewBag.Score = translations["Score"];
            ViewBag.Percentage = translations["Percentage"];
            ViewBag.Pass = translations["Pass"];
            ViewBag.Fail = translations["Fail"];
            ViewBag.NotCompleted = translations["NotCompleted"];
            ViewBag.Hours = translations["Hours"];
            ViewBag.Minutes = translations["Minutes"];
            ViewBag.Seconds = translations["Seconds"];
            ViewBag.Back = translations["Back"];
            ViewBag.Question = translations["Question"];
            ViewBag.YourAnswer = translations["YourAnswer"];
            ViewBag.CorrectAnswer = translations["CorrectAnswer"];
            ViewBag.Explanation = translations["Explanation"];
            ViewBag.SingleChoice = translations["SingleChoice"];
            ViewBag.MultipleChoice = translations["MultipleChoice"];
            ViewBag.TrueFalse = translations["TrueFalse"];
            ViewBag.FillBlank = translations["FillBlank"];
            ViewBag.TrueText = translations["True"];
            ViewBag.FalseText = translations["False"];
            ViewBag.TrueValue = translations["TrueValue"];
            ViewBag.FalseValue = translations["FalseValue"];


            double fenshu = 0;
            foreach (var item in result.UserAnswers)
            {
                fenshu += item.Score;
            }
            ViewBag.fenshu = fenshu;
            return View(result);
        }

        // 我的考试记录
        public ActionResult MyExamResults()
        {
            var userId = (int)Session["UserId"];
            var results = db.ExamResults
                .Include("Exam")
                .Where(r => r.UserId == userId)
                .OrderByDescending(r => r.StartTime)
                .ToList();

            return View(results);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }



        // 开始练习
        public ActionResult StartPractice(int id)
        {
            var exam = db.Exams
                .Include("Questions")
                .Include("Questions.Options")
                .FirstOrDefault(e => e.ExamId == id);

            if (exam == null)
            {
                var translations1 = GetTranslations("ExamNotFound", "Back");
                TempData["ErrorMessage"] = translations1["ExamNotFound"];
                return RedirectToAction("Index");
            }

            var translations = GetTranslations(
                "PracticeMode", "Question", "Score", "SingleChoice",
                "MultipleChoice", "TrueFalse", "FillBlank", "Submit",
                "Back", "Next", "Previous", "Finish", "True", "False",
                "CorrectAnswer", "YourAnswer", "Options", "CheckAnswer",
                "Explanation", "ContinuePractice"
            );

            ViewBag.PageTitle = translations["PracticeMode"] + " - " + exam.ExamName;
            ViewBag.Question = translations["Question"];
            ViewBag.Score = translations["Score"];
            ViewBag.SingleChoice = translations["SingleChoice"];
            ViewBag.MultipleChoice = translations["MultipleChoice"];
            ViewBag.TrueFalse = translations["TrueFalse"];
            ViewBag.FillBlank = translations["FillBlank"];
            ViewBag.Submit = translations["Submit"];
            ViewBag.Back = translations["Back"];
            ViewBag.Next = translations["Next"];
            ViewBag.Previous = translations["Previous"];
            ViewBag.Finish = translations["Finish"];
            ViewBag.True = translations["True"];
            ViewBag.False = translations["False"];
            ViewBag.CorrectAnswer = translations["CorrectAnswer"];
            ViewBag.YourAnswer = translations["YourAnswer"];
            ViewBag.Options = translations["Options"];
            ViewBag.CheckAnswer = translations["CheckAnswer"];
            ViewBag.Explanation = translations["Explanation"];
            ViewBag.ContinuePractice = translations["ContinuePractice"];

            // 创建练习会话记录
            var practiceSession = new PracticeSession
            {
                UserId = (int)Session["UserId"],
                ExamId = id,
                StartTime = DateTime.Now,
                TotalQuestions = exam.Questions.Where(x=>x.IsActive).ToList().Count
            };

            db.PracticeSessions.Add(practiceSession);
            db.SaveChanges();

            Session["CurrentPracticeSessionId"] = practiceSession.SessionId;

            return View(exam);
        }

        // 提交练习答案
        [HttpPost]
        public ActionResult SubmitPracticeAnswer(int examId, int questionId, string userAnswer, string userAnswerText, string correctAnswer, string correctAnswerText)
        {
            // 检查 Session 中是否有练习会话 ID
            if (Session["CurrentPracticeSessionId"] == null)
            {
                return Json(new { success = false, message = "练习会话不存在" });
            }

            var sessionId = (int)Session["CurrentPracticeSessionId"];
            var session = db.PracticeSessions.Find(sessionId);

            if (session == null)
            {
                return Json(new { success = false, message = "练习会话不存在" });
            }

            var question = db.Questions
                .Include("Options")
                .FirstOrDefault(q => q.QuestionId == questionId);

            if (question == null)
            {
                return Json(new { success = false, message = "题目不存在" });
            }

            // 直接使用前端传递的正确答案和文字描述
            string processedCorrectAnswer = correctAnswer ?? question.CorrectAnswer;
            string processedCorrectAnswerText = correctAnswerText ?? question.CorrectAnswer;

            // 处理用户答案的文字描述
            string processedUserAnswerText = "";
            switch (question.QuestionType)
            {
                case "Single":
                case "Multiple":
                    processedUserAnswerText = string.IsNullOrEmpty(userAnswerText) ?
                        GetUserAnswerText(question, userAnswer) : userAnswerText;
                    break;
                case "TrueFalse":
                    processedUserAnswerText = userAnswer == "True" ?
                        LanguageManager.GetText("TrueValue", LanguageManager.GetCurrentLanguage()) :
                        LanguageManager.GetText("FalseValue", LanguageManager.GetCurrentLanguage());
                    break;
                case "Fill":
                    processedUserAnswerText = userAnswer;
                    break;
                default:
                    processedUserAnswerText = string.IsNullOrEmpty(userAnswerText) ? userAnswer : userAnswerText;
                    break;
            }

            // 检查答案是否正确（使用前端传递的正确答案进行比较）
            bool isCorrect = CheckAnswer(question, userAnswer, processedCorrectAnswer);

            // 保存练习答案
            var practiceAnswer = new PracticeAnswer
            {
                SessionId = sessionId,
                QuestionId = questionId,
                UserAnswer = userAnswer ?? "",
                UserAnswerText = processedUserAnswerText ?? "",
                IsCorrect = isCorrect,
                CorrectAnswer = processedCorrectAnswer,
                CorrectAnswerText = processedCorrectAnswerText,
                AnswerTime = DateTime.Now
            };

            db.PracticeAnswers.Add(practiceAnswer);

            // 更新会话统计
            if (isCorrect)
            {
                session.CorrectAnswers++;
            }

            db.Entry(session).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            // 准备返回结果
            var translations = GetTranslations(
                "Correct", "Incorrect", "YourAnswer", "CorrectAnswer",
                "Explanation", "Continue"
            );

            var result = new
            {
                success = true,
                isCorrect = isCorrect,
                userAnswer = userAnswer,
                userAnswerText = processedUserAnswerText,
                correctAnswer = processedCorrectAnswer,
                correctAnswerText = processedCorrectAnswerText,
                message = isCorrect ? translations["Correct"] : translations["Incorrect"],
                yourAnswerText = translations["YourAnswer"],
                correctAnswerTextLabel = translations["CorrectAnswer"],
                explanationText = translations["Explanation"],
                continueText = translations["Continue"]
            };

            return Json(result);
        }

        // 结束练习
        public ActionResult EndPractice()
        {
            if (Session["CurrentPracticeSessionId"] == null)
            {
                return RedirectToAction("Index");
            }

            var sessionId = (int)Session["CurrentPracticeSessionId"];
            var session = db.PracticeSessions
                .Include("Exam")
                .Include("PracticeAnswers")
                .Include("PracticeAnswers.Question")
                .FirstOrDefault(s => s.SessionId == sessionId);

            if (session == null)
            {
                return RedirectToAction("Index");
            }

            // 更新结束时间
            session.EndTime = DateTime.Now;
            db.Entry(session).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            Session.Remove("CurrentPracticeSessionId");

            var translations = GetTranslations(
                "PracticeResult", "ExamName", "StartTime", "EndTime",
                "TotalQuestions", "CorrectAnswers", "Accuracy", "Back"
            );

            ViewBag.PracticeResult = translations["PracticeResult"];
            ViewBag.ExamName = translations["ExamName"];
            ViewBag.StartTime = translations["StartTime"];
            ViewBag.EndTime = translations["EndTime"];
            ViewBag.TotalQuestions = translations["TotalQuestions"];
            ViewBag.CorrectAnswers = translations["CorrectAnswers"];
            ViewBag.Accuracy = translations["Accuracy"];
            ViewBag.Back = translations["Back"];

            return View(session);
        }

        // 练习历史记录
        public ActionResult PracticeHistory()
        {
            var userId = (int)Session["UserId"];
            var sessions = db.PracticeSessions
                .Include("Exam")
                .Where(s => s.UserId == userId)
                .OrderByDescending(s => s.StartTime)
                .ToList();

            var translations = GetTranslations(
                "PracticeHistory", "ExamName", "StartTime", "EndTime",
                "TotalQuestions", "CorrectAnswers", "Accuracy", "ViewDetails",
                "NoPracticeRecords", "Back"
            );

            ViewBag.PracticeHistory = translations["PracticeHistory"];
            ViewBag.ExamName = translations["ExamName"];
            ViewBag.StartTime = translations["StartTime"];
            ViewBag.EndTime = translations["EndTime"];
            ViewBag.TotalQuestions = translations["TotalQuestions"];
            ViewBag.CorrectAnswers = translations["CorrectAnswers"];
            ViewBag.Accuracy = translations["Accuracy"];
            ViewBag.ViewDetails = translations["ViewDetails"];
            ViewBag.NoPracticeRecords = translations["NoPracticeRecords"];
            ViewBag.Back = translations["Back"];

            return View(sessions);
        }

        // 练习详情
        public ActionResult PracticeDetails(int id)
        {
            // 先获取用户ID，避免在LINQ查询中使用Session
            var userId = (int)Session["UserId"];

            var session = db.PracticeSessions
                .Include("Exam")
                .Include("PracticeAnswers")
                .Include("PracticeAnswers.Question")
                .Include("PracticeAnswers.Question.Options") // 添加这个Include以确保选项数据可用
                .FirstOrDefault(s => s.SessionId == id && s.UserId == userId);

            if (session == null)
            {
                return HttpNotFound();
            }

            var translations = GetTranslations(
                "PracticeDetails", "Question", "YourAnswer", "CorrectAnswer",
                "Result", "Explanation", "Correct", "Incorrect", "Back",
                "SingleChoice", "MultipleChoice", "TrueFalse", "FillBlank",
                "True", "False", "Options", "Score", "NotAnswered",
                "FillBlankNoOptions", "NoAnswerDetails"
            );

            ViewBag.PracticeDetails = translations["PracticeDetails"];
            ViewBag.Question = translations["Question"];
            ViewBag.YourAnswer = translations["YourAnswer"];
            ViewBag.CorrectAnswer = translations["CorrectAnswer"];
            ViewBag.Result = translations["Result"];
            ViewBag.Explanation = translations["Explanation"];
            ViewBag.Correct = translations["Correct"];
            ViewBag.Incorrect = translations["Incorrect"];
            ViewBag.Back = translations["Back"];
            ViewBag.SingleChoice = translations["SingleChoice"];
            ViewBag.MultipleChoice = translations["MultipleChoice"];
            ViewBag.TrueFalse = translations["TrueFalse"];
            ViewBag.FillBlank = translations["FillBlank"];
            ViewBag.TrueText = translations["True"];
            ViewBag.FalseText = translations["False"];
            ViewBag.Options = translations["Options"];
            ViewBag.Score = translations["Score"];
            ViewBag.NotAnswered = translations["NotAnswered"];
            ViewBag.FillBlankNoOptions = translations["FillBlankNoOptions"];
            ViewBag.NoAnswerDetails = translations["NoAnswerDetails"];

            return View(session);
        }

    }
}